<?php

namespace App\Console\Commands\Elasticsearch;

use File;

trait Common
{
    /**
     * 获取定义ES的模型
     * @return Collection
     * @throws BindingResolutionException
     */
    protected function getModels()
    {
        $modelDir = app()->publicPath() . "/modules/{$this->module}/Entities";

        return collect(File::files($modelDir))->map(function ($file) {
            $modelName = substr($file->getBasename(), 0, -4);

            return "Modules\\{$this->module}\\Entities\\{$modelName}";
        })->filter(function ($class) {
            $ref = new \ReflectionClass($class);
            $state = $ref->hasMethod('elasticsearchMapping');

            if ($state) {
                $reflectionMethod = new \ReflectionMethod($class, 'elasticsearchEnable');

                $isEnable =  $reflectionMethod->invoke(new $class, 'elasticsearchEnable');
                return $state && $isEnable;
            }
            return $state;
        });
    }

    /**
     * 根据模型类型获取 ES索引名称
     * @param string $class
     * @return string
     */
    protected function getIndexNameByModelClass(string $class)
    {
        $refClass = new \ReflectionClass($class);
        return strtolower('edu' . $refClass->getShortName());
    }
}
